package com.cdu.service.impl;

import com.cdu.commons.ServiceCode;
import com.cdu.commons.ServiceException;
import com.cdu.mapper.OrderMapper;
import com.cdu.mapper.ProductMapper;
import com.cdu.pojo.dto.OrderCreateDTO;
import com.cdu.pojo.entity.Order;
import com.cdu.pojo.entity.User;
import com.cdu.pojo.vo.OrderVO;
import com.cdu.service.OrderService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired private OrderMapper orderMapper;
    @Autowired private ProductMapper productMapper;

    @Override
    @Transactional
    public void createOrder(OrderCreateDTO orderCreateDTO, User user) {
        if (orderCreateDTO == null) {
            throw new ServiceException("订单参数不能为空", ServiceCode.PARAM_ERROR);
        }

        try {
            Order order = new Order();
            BeanUtils.copyProperties(orderCreateDTO, order);
            order.setRecvProvince(orderCreateDTO.getRecvProvince());
            order.setOrderTime(new Date());
            order.setCreatedUser(user.getUsername());
            orderMapper.insertOrder(order);
        } catch (ServiceException e) {
            log.error("创建订单失败", e);
            throw e;
        } catch (Exception e) {
            log.error("创建订单未知异常", e);
            throw new ServiceException("创建订单失败", ServiceCode.UNKNOWN_ERROR);
        }
    }

    @Override
    public OrderVO getOrderById(Integer Id) {
        Order order = orderMapper.getOrderById(Id);
        if (order == null) throw new ServiceException("订单不存在", ServiceCode.DATA_NOT_FOUND);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        return orderVO;
    }

    private String getOrderStatusText(Integer status) {
        switch (status) {
            case 0: return "待付款";
            case 1: return "待发货";
            case 2: return "已发货";
            case 3: return "已完成";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }


    @Override
    public void updateOrderStatus(Integer orderId, Integer status, User user) {
        if (orderMapper.updateOrderStatus(orderId, status) != 1) {
            throw new ServiceException("更新订单状态失败", ServiceCode.DB_ERROR);
        }
    }

    @Override
    public void deleteOrder(Integer orderId, User user) {
        if (orderMapper.deleteOrder(orderId) != 1) {
            throw new ServiceException("删除订单失败", ServiceCode.DB_ERROR);
        }
    }


}